package com.ruoyi.web.East;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

@Component
@Slf4j
public class TcpClient implements CommandLineRunner {

    /**
     * 监听的端口
     */
    final static int port = 7777;

    @Override
    public void run(String... args) throws Exception {
        startAction();
    }

    public void startAction() {
        // 使用 try-with-resources 确保 ServerSocket 资源被自动关闭
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            log.info("<----------socket服务端启动监听成功！, 监听端口: " + port + "---------->");

            // 通过死循环开启长连接，开启线程去处理消息
            while (!Thread.currentThread().isInterrupted()) {
                //从连接请求队列中取出一个连接
                Socket socket = serverSocket.accept();
                new Thread(new SocketServer(socket)).start();
            }
        } catch (IOException e) {
            log.error("<----------socket服务端启动监听失败!---------->", e);
            throw new RuntimeException(e);
        }
    }
}
